package totask.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import totask.feign.UserInfoClient;
import totask.pojo.UserInfo;
import totask.redis.RedisCache;
import totask.response.ResponseData;
import totask.service.LoginService;
import totask.vo.LoginInfoVO;
import totask.vo.LoginUserInfoVO;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserInfoClient userInfoClient;

    @Autowired
    RedisCache redisCache;
    @Override
    public ResponseData<LoginUserInfoVO> LoginUser(LoginInfoVO loginInfoVO) {
        Map<String, Object> userinfoMap = null;
        UserInfo userinfo = new UserInfo();
        LoginUserInfoVO loginUserInfoVO=new LoginUserInfoVO();
        System.out.println(loginInfoVO.toString());
        try {
            //在网关服务中，使用远程调用调用，必须使用异步调用
            CompletableFuture<Object> completableFuture = CompletableFuture.supplyAsync(() -> {
                return userInfoClient.userLogin(loginInfoVO.getUserName(), loginInfoVO.getPassWord());
            });
            //获取调用数据
            userinfoMap= (Map<String, Object>) completableFuture.get();
        } catch (Exception e) {
            System.out.println("远程调用请求出错" + e);
        }

        //对象复制
        BeanUtil.copyProperties(userinfoMap.get("data"),userinfo);

        //校验失败了，判断如果data返回为空，则就是没有这个用户，不在继续执行，直接返回登录失败
        if(!Objects.isNull(userinfo.getUserId())){
            //登录
            StpUtil.login(userinfo.getUserId());
            //设置token
            loginUserInfoVO.setToken(StpUtil.getTokenInfo().getTokenValue());
            loginUserInfoVO.setUserInfo(userinfo);
            //系统用户相关所有信息放入redis
            redisCache.setCacheObject("login:"+userinfo.getUserId(),loginUserInfoVO);
        }

        System.out.println("角色："+StpUtil.getRoleList());
        System.out.println("角色："+StpUtil.hasPermission("system"));


        return new ResponseData<LoginUserInfoVO>().success(loginUserInfoVO);
    }
}
